# -*- coding: utf-8 -*-
# @Author	: changfeng
# @Date		: 2024/11/20 20:45
# @Last Modified by:   changfeng
# @Last Modified time: 2024/11/20 20:45
# Thanks for your comments!


import logging
import traceback

import asyncio
import pydantic
from src.basedata.infrastructure.utils.message import check_post_params

from src.seedwork.application import responses
from src.basedata.application.commands import COMMAND_METHODS_MAP
from src.seedwork.infrastructure.exceptions import UnknownCommand

logger = logging.getLogger(__name__)


async def handle_common(m, bus) -> responses.Response:
    try:
        logger.info("handling {0}".format(str(m).encode("utf-8")))
        data = m
        check_ret = check_post_params(data, ["bizCode", "data"])
        if check_ret is not True:
            logger.error("Error request: {0}".format(check_ret))
            return responses.ParamsCheckErrorResponse()
        handle_class = COMMAND_METHODS_MAP.get(data["bizCode"])
        if not handle_class:
            logger.error("Unknown bizCode: {0}".format(data["bizCode"]))
            return responses.UnknownBizCodeResponse()
        # 这里先特殊处理一下吧,后面找到事哪个服务调用的话，改一下那边的请求参数格式
        if data["bizCode"] == "sync_person":
            data['data'] = {
                "data": data.pop("data", {})
            }
        return await bus.handle(handle_class(**data['data']))
    except UnknownCommand as u:
        return responses.UnknownBizCodeResponse(str(u))
    except pydantic.error_wrappers.ValidationError as ve:
        logger.warning(f'param is not valid for {m}. err:{str(ve)}')
        return responses.ParamsCheckErrorResponse(str(ve))
    except asyncio.TimeoutError as te:
        logger.warning(f'handle timeout for {m}. err:{str(te)}')
        return responses.TimeoutErrorResponse()
    except KeyError as ke:
        logger.warning(f'param is not valid for {m}. err:{str(ke)}')
        return responses.UnknownFoundHandleResponse(str(ke))
    except Exception as e:
        logger.info(traceback.print_exc())
        return responses.ExceptionResponse(str(e))
